package com.neborosoft.lib.stream;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 09.11.12
 * Time: 7:44
 * To change this template use File | Settings | File Templates.
 */
public final class Stream {
    public static InputStream getInputStreamFromUrl(String url) throws IOException{
        URLConnection connection = null;
        try {
            connection = new URL(url).openConnection();
        } catch (MalformedURLException e) {
            connection = new URL("file:" + url).openConnection();
        }
        return connection.getInputStream();
    }

    public static InputStream getBufferedInputStream(InputStream stream){
        if(stream instanceof BufferedInputStream){
            return stream;
        } else {
            return new BufferedInputStream(stream);
        }
    }

    public static OutputStream getBufferedOutputStream(OutputStream stream){
        if(stream instanceof BufferedOutputStream){
            return stream;
        } else {
            return new BufferedOutputStream(stream);
        }
    }

    public static InputStream getBufferedInputStreamFromUrl(String url) throws IOException{
        InputStream stream = getInputStreamFromUrl(url);
        return getBufferedInputStream(stream);
    }

    public static boolean createFile(String path) throws IOException {
        File file = new File(path);
        if(file.isDirectory()){
            file.delete();
        }
        return file.createNewFile();
    }

    public static FileInputStream getOrCreateFileInputStream(String url) throws IOException {
        createFile(url);
        return new FileInputStream(url);
    }

    public static InputStream getOrCreateFileBufferedInputStream(String url) throws IOException {
        FileInputStream stream = getOrCreateFileInputStream(url);
        return getBufferedInputStream(stream);
    }

    public static FileOutputStream getOrCreateFileOutputStream(String url) throws IOException {
        createFile(url);
        return new FileOutputStream(url);
    }

    public static OutputStream getOrCreateFileBufferedOutputStream(String url) throws IOException {
        FileOutputStream stream = getOrCreateFileOutputStream(url);
        return getBufferedOutputStream(stream);
    }

    public static InputStream getBufferedInputStreamFromUrl(String url, int buffSize) throws IOException{
        InputStream stream = getInputStreamFromUrl(url);
        return new BufferedInputStream(stream,buffSize);
    }
}
